#!/usr/bin/env python
from google.appengine.ext import db
import logging
import GeneralM
import TopicM
import QuestionM

def updateStudentVote(studentKey,lectureKey,understand):
    stud = None
    
    #lecture=LectureM.getLectureByKey(lectureKey)
#    classState=ClassM.getClassByLectureKey(lectureKey)
    currTopic=ClassM.getCurrentTopic(lectureKey)
    
    if studentKey:
        try:
            stud=StudentVote.get(studentKey)
            if stud.topic.key() != currTopic.key():
                logging.debug("stud.topic: "+str(stud.topic.key()) + ", currTopic:"+str(currTopic.key()))
                stud=None
        except Exception, exc:
            logging.debug("studentKey: "+studentKey + ", Exception Thrown\n")
            stud=None
    
    logging.debug("updateStudentVote, currTopic:"+str(currTopic))
    # Creates new student object
    if stud is None:
        stud=StudentVote(topic=currTopic)
    
    # Update Value
    if(understand=='true'): 
            stud.understand=True
    else:
            stud.understand=False
    
    stud.put()
    return str(stud.key())

def getStudentVotesStats(topicKey):
    owner = GeneralM.getEmail()
    currTopic=TopicM.getTopicByKey(topicKey)
    if owner and topicKey:
        allStudentsQuery = db.Query(StudentVote).filter('topic =',currTopic)
        totalStudents=allStudentsQuery.count()
        confusedStudents=allStudentsQuery.filter('understand = ',True).count()
        return {'voiceTotal': totalStudents, 'voiceUnderstand': confusedStudents}
    else:
        return 'error:user accessed lecture key of another user'

def deleteOldStudentVotes(lectureKey):
    owner = GeneralM.getEmail()
    lecture=LectureM.getLectureByKey(lectureKey)
    if(lecture.course.owner == owner):
        topics=TopicM.getTopicsByLecture(lecture)
        for topic in topics:
            db.delete(db.Query(StudentVote).filter('topic = ', topic))

def deletePrevStudentVotes(topicKey):
    owner = GeneralM.getEmail()
    if owner:
        topic=TopicM.getTopicByKey(topicKey)
        if(topic.lecture.course.owner == owner):
            db.delete(db.Query(StudentVote).filter('topic = ', topic ))

class StudentVote(db.Model):
    topic = db.ReferenceProperty(TopicM.Topic)
    understand = db.BooleanProperty()
    when = db.DateTimeProperty(auto_now=True)

def updateStudentAnswer(questionKey, answer):
    question=QuestionM.getQuestionByKey(questionKey)
    if question:
        studentAnswer=StudentAnswer(question = question, answerIndex=int(answer))
        studentAnswer.put()
        
def getQuestionData(questionKey):
    if questionKey:
        question=QuestionM.getQuestionByKey(questionKey)
        if question:
            data=[]
            for answerIndex in range(len(question.answers)):
                answersQuery=db.Query(StudentAnswer).filter('question = ', question)
                data.append(answersQuery.filter('answerIndex = ', answerIndex).count())
            return data
        else:
            return None

def deleteOldStudentAnswers(question):
    if question:
        db.delete(db.Query(StudentAnswer).filter('question = ', question))

class StudentAnswer(db.Model):
    question = db.ReferenceProperty(QuestionM.Question)
    answerIndex = db.IntegerProperty()
    when = db.DateTimeProperty(auto_now=True)

import LectureM
import ClassM